package com.Logistics.mycommon.tools;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class GaodMap {
    public Long  Distance(String startPoint,String endPoint) {
//        String startPoint="113.568824,34.807564";
//        String endPoint="114.657485,34.745224";
        //59.0190199454325

        Double dis       = getDis(Double.parseDouble(startPoint.substring(startPoint.indexOf(",")+1)),
                Double.parseDouble(startPoint.substring(0,startPoint.indexOf(","))),
                Double.parseDouble(endPoint.substring(endPoint.indexOf(",")+1)),
                Double.parseDouble(endPoint.substring(0,endPoint.indexOf(","))));
        System.out.println("计算距离结果:"+dis);
        long distance = getDistance(startPoint, endPoint);
        System.out.println("api调用距离结果:"+distance);
        return distance;
    }

    /**
     * 1.直接程序计算
     */
    public static Double getDis(Double lat1,Double lon1,Double lat2,Double lon2 ){
        Double radLat1=(lat1 * Math.PI) /180;
        Double radLat2=(lat2 * Math.PI) /180;
        Double a=radLat1-radLat2;
        Double b=(lon1 * Math.PI) /180 -(lon2 * Math.PI)/180;
        Double s=2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
                Math.sin(b / 2), 2)));
        s=s* 6378137.0;
        return s;
    }


    /**
     * 2.经纬度算出两点间距离（通过api调用计算）
     *
     */
    public static long getDistance(String startLonLat, String endLonLat){
        Long result = 0L;
        String queryUrl = "http://restapi.amap.com/v3/distance?key="+"6cb244f1a67c3bf042f489c2be3b76dc"+"&origins="+startLonLat+"&destination="+endLonLat+"&type=0";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(queryUrl);
            CloseableHttpResponse response = httpClient.execute(httpGet);

            try {
                HttpEntity entity = response.getEntity();
                String queryResult = EntityUtils.toString(entity);
                JSONObject job = JSONObject.parseObject(queryResult);
                JSONArray ja = job.getJSONArray("results");
                if (ja != null && ja.size() > 0) {
                    JSONObject jobO = ja.getJSONObject(0);
                    result = Long.parseLong(jobO.getString("distance"));
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
         return result;
    }
}
